import os

from django.core.paginator import Paginator
from django.db import transaction
from django.db.models import Q, Sum, Max, Min, Avg
from django.http import HttpResponse
from django.shortcuts import render, redirect

# Create your views here.

# Q函数
# def query_course(request):
#     c = request.GET.get('c', None)
#     query = Q()
#     if c is not None:
#         query = query & Q()
#     sort = request.GET.get('sort', None)
#     if sort is not None:
#         query = query & Q()
from django.views.generic import ListView

from accounts.forms import LoginForm, UserEditForm, UserRegForm, UserChangeForm, AvatarUploadForm
from accounts.models import User, Profile, Grade
from my_project.settings import MEDIA_ROOT


def user_info(request):
    """用户详情查询优化"""
    user = User.objects.get(pk=1)
    profile_list = Profile.objects.all().select_related('user')
    # profile_list = Profile.objects.all()

    # SQL查询
    user_list = User.objects.raw('SELECT * FROM `accounts_users`')
    return render(request, 'user_info.html', {
        'user': user,
        'profile_list': profile_list,
        'user_list': user_list,
    })


def user_list_paginator(request):
    """分页器分页"""
    page = request.GET.get('page', 1)
    user_list = User.objects.all()
    # 第一步取得分页器
    p = Paginator(user_list, 15)
    # 第二步取得某一页对象
    page_data = p.get_page(page)

    return render(request, 'user_list_paginator.html', {
        'page_data': page_data,
    })


class UserListView(ListView):
    """面向对象 分页处理"""
    template_name = 'user_list_class.html'
    model = User
    paginate_by = 20
    page_kwarg = 'p'


def page_grade(request):
    """成绩统计"""
    stu = request.GET.get('stu')
    sub = request.GET.get('sub')
    method = request.GET.get('method', 'sum')
    total_list = []
    total = []
    if stu:
        grade_list = Grade.objects.filter(student_name=stu)
        total = grade_list.aggregate(total_score=Sum('score'))
    elif sub:
        grade_list = Grade.objects.filter(subject_name='数学')
        if method == 'max':
            total = grade_list.aggregate(max_score=Max('score'))
        elif method == 'min':
            total = grade_list.aggregate(min_score=Min('score'))
        elif method == 'avg':
            total = grade_list.aggregate(avg_score=Avg('score'))
    else:
        total_list = Grade.objects.values('student_name').annotate(sum_score=Sum('score')).order_by('student_name')

    return render(request, 'page_grade.html', {
        'total': total,
        'student_name': stu,
        'subject_name': sub,
        'total_list': total_list,
    })


def user_register(request):
    """用户注册"""
    try:
        # 获取表单数据
        # 验证数据符合要求
        # 添加用户信息（基本 详细）
        username = '1303'
        user = User.objects.create(username=username, password='123456', nickname='wang')
        profile = Profile.objects.create(user=user, username=username)
        # 反馈结果
        return HttpResponse('ok')
    except Exception as e:
        user.delete()
        print(e)
        return HttpResponse('no')


@transaction.atomic()
def user_signup(request):
    """trac自动化事务"""
    username = '1301'
    user = User.objects.create(username=username, password='123456', nickname='wang')
    profile = Profile.objects.create(user=user, usernamex=username)
    return HttpResponse('ok')


def user_signup_with(request):
    """trac自动化事务"""
    with transaction.atomic():
        username = '1301'
        user = User.objects.create(username=username, password='123456', nickname='wang')
        profile = Profile.objects.create(user=user, usernamex=username)
        return HttpResponse('ok')


def user_signup_hand(request):
    """用户注册"""
    transaction.set_autocommit(False)
    try:
        # 获取表单数据
        # 验证数据符合要求
        # 添加用户信息（基本 详细）
        username = '1302'
        user = User.objects.create(username=username, password='123456', nickname='wang')
        profile = Profile.objects.create(user=user, username=username)
        transaction.commit()
        # 反馈结果
        return HttpResponse('ok')
    except Exception as e:
        transaction.rollback()
        print(e)
        return HttpResponse('no')


def user_login(request):
    """用户登录"""
    form = LoginForm()
    if request.method =='POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            print('表单验证通过')
        else:
            print(form.errors)
    else:
        form = LoginForm()
    return render(request, 'user_login.html', {
        'form': form,
    })


def user_edit(request):
    """用户信息维护"""
    if request.method == 'POST':
        form = UserEditForm(data=request.POST)
        if form.is_valid():
            print('表单通过验证')
    else:
        form = UserEditForm()
    return render(request, 'user_edit.html', {
        'form': form,
    })


def user_reg(request):
    """用户注册"""
    if request.method == 'POST':
        data = request.POST
        print('post data:', data)
        form = UserRegForm(data=request.POST,files=request.FILES)
        # 是否通过验证
        if form.is_valid():
            form_data = form.cleaned_data
            print('验证通过后的数据：', form_data)
        else:
            print(form.errors)
    else:
        initial_data = {
            'nickname': '默认昵称',
            'birth_date': '2020-01-01'
        }
        form = UserRegForm(initial=initial_data)
    return render(request, 'user_reg.html', {
        'form': form,
    })


def user_change(request):
    """用户信息维护--基于ORM"""
    if request.method == 'POST':
        form = UserChangeForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            data = form.cleaned_data
            form.save()
            print('表单通过验证')
            return redirect('/accounts/user/login')
    else:
        form = UserChangeForm()
    return render(request, 'user_change.html', {
        'form': form,
    })


def upload_user_form(request):
    """文件上传-表单"""
    if request.method == 'POST':
        file = request.FILES.get('avatar', None)
        if file:
            filename = os.path.join( MEDIA_ROOT,'test_form.jpg')
            with open(filename,'wb+') as dest:
                for chunk in file.chunks():
                    dest.write(chunk)
                print('文件上传成功')
    return render(request, 'upload_user_form.html')


def upload_user_form2(request):
    """文件上传-django表单"""
    if request.method == 'POST':
        form = AvatarUploadForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            file = form.cleaned_data['avatar']
            filename = os.path.join(MEDIA_ROOT, 'avatar.jpg')
            with open(filename, 'wb+') as dest:
                for chunk in file.chunks():
                    dest.write(chunk)
                print('文件上传成功')
    else:
        form = AvatarUploadForm()
    return render(request, 'upload_user_form2.html', {
        'form': form,
    })
